<?php
/**
 * test
 * User: bgl
 * Date: 2022/10/17
 * Time: 13:42
 */

namespace App\Logic\Test;

use App\Console\Commands\Rakuten\SyncRakutenInventory;
use App\Jobs\Stocking\AreaEuEstimateJob;
use App\Jobs\Stocking\AreaEuSkuRatioJob;
use App\Jobs\Stocking\CountryEstimateJob;
use App\Libs\Rakuten\Common\RakutenClient;
use App\Logic\Plat\Rakuten\GrabOrders;
use App\Logic\Plat\Rakuten\Overseas\GuCang\InboundOrder\OverseasInboundOrder;
use App\Logic\Plat\Rakuten\Overseas\GuCang\Inventory\OverSeasInventory;
use App\Logic\Plat\Rakuten\Overseas\GuCang\Order\OverseasOrder;
use App\Logic\Plat\SyncPlatOrder;
use App\Logic\SalesAmazon\SalesAmountDaily;
use App\Models\Amazon\FbaCustomerReturn;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\SysICountry;
use App\Models\Basics\SysPlat;
use App\Models\Basics\SysPlatCountry;
use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\CustomerDelivery\CustomerDeliveryReceiver;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\CustomerDelivery\CustomerOrderDetails;
use App\Models\CustomerDelivery\CustomerOrderReceiver;
use App\Models\OverSeasBa\DropshippingInventoryFnsku;
use App\Models\OverSeasBa\RemovaleInventoryFNSku;
use App\Models\OverSeasIn\RemovaleOrderDetail;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductRakutenSku;
use App\Models\Product\ProductShopifySku;
use App\Models\Product\ProductShopifySkuCCS;
use App\Models\Product\ProductSku;
use App\Models\Rakuten\RakutenOrder;
use App\Models\Rakuten\RakutenOrderItem;
use App\Models\SalesAmazon\SalesAmountDay;
use App\Models\SalesAmazon\SalesAmountMonth;
use App\Models\SalesAmazon\SalesVolumeDay;
use App\Models\SalesAmazon\SalesVolumeMonth;
use App\Models\SalesReport\DailyVolume;
use App\Models\SalesReport\FBAInventory;
use App\Models\Shipping\SSku;
use App\Models\Shipping\SSkuApply;
use App\Models\SsBasic\AreaClassifyEstimate;
use App\Models\SsBasic\AreaSkuEstimate;
use App\Models\SsBasic\CountryClassifyEstimate;
use App\Models\SsBasic\CountrySku;
use App\Models\SsBasic\CountrySkuAvg;
use App\Models\SsBasic\CountrySkuEstimate;
use App\Models\SsBasic\CountrySkuStock;
use App\Models\SsBasic\CountryStockingSku;
use App\Models\SsBasic\CountryStockingSkuRatio;
use App\Models\SsBasic\JpClassifyEstimate;
use App\Models\SsBasic\JpSku;
use App\Models\SsBasic\JpSkuAvg;
use App\Models\SsBasic\JpSkuEstimate;
use App\Models\SsBasic\JpSkuStock;
use App\Models\SsBasic\JpStockingSku;
use App\Models\SsBasic\JpStockingSkuRatio;
use App\Models\Stocking\StockingSku;
use App\Models\Stocking\StockingSkuRatio;
use Illuminate\Support\Facades\DB;

class Test{

    public static function work(){
        ini_set('memory_limit', '1024M');
        set_time_limit(0);

        $estimate = CountryClassifyEstimate::query()->get();
        self::exeFillData($estimate);
    }

    public static function test(){

        $i = 0;
        $err = [];
        CustomerDeliveryDetail::query()
            ->where('created_at', '>=', '2024-11-01 00:00:00')
            ->chunk(500, function ($items) use (&$i,&$err){
                foreach ($items as $item) {
                    //验证,更新订单状态
                    $deliveryDetailStatusArr = CustomerDeliveryDetail::query()
                        ->where('order_no',$item->order_no)
                        ->pluck('status')
                        ->toArray();
                    if($deliveryDetailStatusArr) {
                        $status = CustomerDeliveryDetail::extractStatus($deliveryDetailStatusArr); //订单状态

                        $flag = CustomerDelivery::query()
                            ->where('delivery_no',$item->delivery_no)
                            ->update([
                                'status' => $status
                            ]); //订单状态
                        if (!$flag) {
                            $err[] = $item->order_no;
                        }
                    }

                    $i++;
                    echo $i . PHP_EOL;
                }
                //sleep(1);
            });
        dd(array_unique($err));
        //GrabOrders::getRakutenOrderBack();
        //dd('aaa');
        //
        //$seller_fulfillment_order_id = 'null';
        //$accountId = 0;
        //SyncPlatOrder::deliveryOrderException($seller_fulfillment_order_id,$accountId);
        //dd(111);

        $arr = [
            //'407083-20241107-0423701967',
            //'407083-20241107-0578501831',
            '407083-20241107-0339502082',
            '407083-20241108-0709202009',
            '407083-20241108-0827001972',
            '407083-20241108-0837601942',
            '407083-20241108-0855701886',
            '407083-20241108-0998201844'
        ];
        $data = array_unique($arr);

        $i = 0;
        $err = [];
        foreach ($data as $item) {
            $rakutenOrder = RakutenOrder::query()->where('order_id',$item)->first();
            if (!$rakutenOrder) {
                $err[] = $item;
                continue;
            }

            ////2.创建erp客户订单
            //$customerOrderFlag = CustomerOrder::addRakutenCustomerOrder([$rakutenOrder]);
            //if (!$customerOrderFlag) continue;
            //sleep(1);

            //2.创建erp客户发货单(FBA发货)
            $customerDeliveryFlag = CustomerOrder::addCustomerDelivery($rakutenOrder,CustomerDelivery::DELIVERY_TYPE_FBA,7);
            if ($customerDeliveryFlag) continue;

            $i++;
            echo $i .'|'. $item.PHP_EOL;
        }
        dd($err);

        //SyncPlatOrder::syncRakutenGuCangTrackingNo();
        //dd('aaa');
        //
        //SyncPlatOrder::syncAmazonOrder('407083-20241204-0095507891', 7);
        //dd('aaa');
        //
        //SyncPlatOrder::syncRakutenOrder('407083-20241205-0002608490', 200000);
        //dd('bbb');

       /* $arr = [
            '407083-20241125-0924805824','407083-20241125-0127906067','407083-20241125-0227905889','407083-20241125-0136406114','407083-20241125-0378905921',
            '407083-20241125-0400405890','407083-20241125-0701305853','407083-20241125-0682005900','407083-20241125-0486206119','407083-20241125-0725405876',
            '407083-20241125-0777205901','407083-20241125-0917506022','407083-20241125-0027606173','407083-20241125-0194906209','407083-20241125-0125606366',
            '407083-20241125-0201106282','407083-20241126-0308906237','407083-20241126-0591706323','407083-20241126-0926306139','407083-20241126-0945006208',
            '407083-20241126-0861606389','407083-20241126-0020306548','407083-20241127-0151306586','407083-20241127-0173706544','407083-20241127-0086906679',
            '407083-20241127-0240506664','407083-20241127-0322306552','407083-20241127-0379406497','407083-20241127-0334906621','407083-20241127-0489606461',
            '407083-20241128-0573506562','407083-20241128-0699006480','407083-20241128-0630606605','407083-20241128-0631906635','407083-20241128-0889006423'
        ];
        $i = 0;
        foreach ($arr as $item) {
            $rakutenOrder = RakutenOrder::query()->where('order_id',$item)->first();
            if (!$rakutenOrder) continue;

            //2.创建erp客户订单
            $customerOrderFlag = CustomerOrder::addRakutenCustomerOrder([$rakutenOrder]);
            if (!$customerOrderFlag) continue;
            sleep(1);

            //3.创建erp客户发货单
            $customerDeliveryFlag = CustomerOrder::addCustomerDelivery($rakutenOrder,CustomerDelivery::DELIVERY_TYPE_ABROAD,200000);
            if (!$customerDeliveryFlag) continue;

            $i++;
            echo $i .'|'. $item.PHP_EOL;

            sleep(1);
        }*/
        dd(111);

        $i = 0;
        $err = [];
        CustomerDelivery::query()
            ->where('status',3)
            ->chunk(100, function ($items) use (&$i,&$err){
                foreach ($items as $item) {

                    //验证,更新订单状态
                    $deliveryDetailStatusArr = CustomerDeliveryDetail::query()
                        ->where('order_no',$item->order_no)
                        ->pluck('status')
                        ->toArray();
                    if($deliveryDetailStatusArr) {
                        $status = CustomerDeliveryDetail::extractStatus($deliveryDetailStatusArr); //订单状态
                        $item->status = $status;
                        $item->save();
                    }

                    $i++;
                    echo $i . PHP_EOL;
                }
                sleep(1);
            });
        dd($err);

        $i = 0;
        $err = [];
        CustomerDelivery::query()
            ->where('delivery_no', 'OPD24112500002')
            ->where('created_at', '>=', '2024-08-01 00:00:00')
            ->groupBy('order_no')
            ->chunk(100, function ($items) use (&$i,&$err){
                foreach ($items as $item) {
                    $customerDelivery = CustomerDelivery::query()->where('order_no',$item->order_no)->first();
                    if ($customerDelivery->detail->isEmpty()) {
                        self::createDeliveryDetail($item->order_no);

                        $err[] = $customerDelivery->order_no;
                    }

                    $i++;
                    echo $i . PHP_EOL;
                }
                sleep(1);
            });
        dd(implode('","',$err));

        /*$i = 0;
        CustomerOrderDetails::query()
            ->where('created_at', '>=', '2024-08-01 00:00:00')
            ->where('plat_id', 3)
            ->where('status', 1)
            ->chunk(100, function ($items) use (&$i){
                foreach ($items as $item) {
                    $rakutenOrder = RakutenOrder::query()->where('order_id',$item->order_no)->first();
                    if (!$rakutenOrder) continue; //原始平台订单

                    if (!empty($item->overseas_order_id)) {
                        //2.创建erp客户发货单(海外仓发货)
                        $customerDeliveryFlag = CustomerOrder::addCustomerDelivery($rakutenOrder,CustomerDelivery::DELIVERY_TYPE_ABROAD,200000);
                        if (!$customerDeliveryFlag) continue;
                    }else{
                        //2.创建erp客户发货单(FBA发货)
                        $customerDeliveryFlag = CustomerOrder::addCustomerDelivery($rakutenOrder,CustomerDelivery::DELIVERY_TYPE_FBA,7);
                        if ($customerDeliveryFlag) continue;
                    }

                    $i++;
                    echo $i . PHP_EOL;
                }
                sleep(1);
            });
        dd('aaa');*/

        $arr = [
            '407083-20241117-0426604008',
            '407083-20241118-0830903865',
            '407083-20241108-0831702042',
            '407083-20241109-0097602176',
            '407083-20241109-0154102387',
            '407083-20241109-0332402139',
            '407083-20241110-0515502242',
            '407083-20241116-0089703888'
            ];
        $i = 0;
        foreach ($arr as $item) {
            //$customerDelivery = CustomerDelivery::query()->where('order_no',$item)->first();
            //if ($customerDelivery) {
            //    $customerDelivery->delete();
            //}
            //$customerOrder = CustomerOrder::query()->where('order_no',$item)->first();
            //if ($customerOrder) {
            //    $customerOrder->delete();
            //}
            //sleep(1);

            $rakutenOrder = RakutenOrder::query()->where('order_id',$item)->first();
            if (!$rakutenOrder) continue;

            //创建erp客户单
            CustomerOrder::addCustomerOrder([$rakutenOrder]);

            ////创建erp客户发货单
            //CustomerOrder::addCustomerDelivery($rakutenOrder,CustomerDelivery::DELIVERY_TYPE_ABROAD);
            sleep(2);

            $i++;
            echo $i . PHP_EOL;
        }
        dd(111);



    }

    public static function createDeliveryDetail($orderNo){
        $rakutenOrder = RakutenOrder::query()->where('order_id',$orderNo)->first();
        if (!$rakutenOrder) return false; //原始平台订单

        $customerOrderObj = CustomerOrder::query()->where('order_no',$orderNo)->first();
        if(!$customerOrderObj) return false; //客户消费订单

        $customerDeliveryObj = CustomerDelivery::query()->where('order_no',$orderNo)->first();
        if(!$customerDeliveryObj) return false; //客户发货订单

        //验证实际发货单号(批次)
        $_deliveryOrderNo = CustomerDeliveryDetail::query()
            ->where('order_no', $orderNo)
            ->orderBy('id', 'DESC')
            ->limit(1)
            ->value('delivery_order_no');
        $deliveryOrderNo = formatStrOrderNo($_deliveryOrderNo) ?? $customerOrderObj->order_no;

        //组装客户订单发货明细数据
        $deliveryDetail = [];

        list($fbaInventoryFlag,$accountId) = FBAInventory::_checkJpFbaInventoryFnsku($rakutenOrder);
        foreach ($customerOrderObj->detail as $key => $item){
            if($item->status == CustomerOrderDetails::ORDER_DELIVERY_CANCEL) continue;

            $warehouseId = 0;
            if ($accountId == 200000) $warehouseId = 69; //日本谷仓ID

            //获取(FBA)发货站点下的账号以及sku可用库存
            $FBAareaInventory = FBAInventory::getFBAInventoryRakuten($customerOrderObj->area_id, $item->psku_id, $accountId);
            $sellerSku = $FBAareaInventory->seller_sku ?? '';

            $deliveryDetail[] = [
                'delivery_no'       => $customerDeliveryObj->delivery_no, //单号
                'order_no'          => $customerDeliveryObj->order_no, //订单号
                'delivery_order_no' => $deliveryOrderNo, //实际发货订单号
                'order_detail_id'   => $item->id, //订单明细id
                'psku_id'           => $item->psku_id ?? 0,
                'seller_sku'        => $sellerSku,
                'plat_id'           => $customerDeliveryObj->plat_id ?? 0,
                'plat_sku'          => $item->plat_sku ?? '',
                'apply_num'         => $item->order_num ?? 0,
                'ship_num'          => 0,
                'account_id'        => $accountId, //默认,乐天账号ID
                'warehouse_id'      => $warehouseId, //默认,日本谷仓ID
                'apply_remarks'     => '',
                'delivery_type'     => $customerDeliveryObj->delivery_type,
                'delivered_at'      => $customerOrderObj->order_at ?? date('Y-m-d H:i:s', time()),
                'status'            => 3,
                'overseas_order_id' => $customerOrderObj->overseas_order_id ?? ''
            ];
        }
        if(count($deliveryDetail) == 0) return false;

        //创建发货明细
        foreach ($deliveryDetail as $value){
            CustomerDeliveryDetail::query()->create($value);
        }

        //创建发货地址
        CustomerDeliveryReceiver::query()->create([
            'delivery_no'       => $customerDeliveryObj->delivery_no, //单号
            'order_no'   => $customerOrderObj->order_no,
            'country'    => $customerOrderObj->receiver->country ?? '',
            'receiver'   => $customerOrderObj->receiver->receiver ?? '',
            'address'    => $customerOrderObj->receiver->address ?? '',
            'state'      => $customerOrderObj->receiver->state ?? '',
            'city'       => $customerOrderObj->receiver->city ?? '',
            'postcode'   => $customerOrderObj->receiver->postcode ?? '',
            'phone'      => $customerOrderObj->receiver->phone ?? ''
        ]);
    }

    public static function testEuStocking(){

        $classifyEstimate = CountryClassifyEstimate::query()
            ->where('classify_id',178)
            ->get();
        if (!$classifyEstimate) dd('die');

        //AreaEuEstimateJob::dispatch($classifyEstimate);
        //AreaEuSkuRatioJob::dispatch($classifyEstimate);
        dd('aaa');
    }

    public static function testRemovaleOrderDetail(){

        //1. 汇总数据（账号、仓库、fnsku） 1666
        $detailList = RemovaleOrderDetail::query()
            ->select('account_id', 'warehouse_id', 'fnsku', 'psku_id', DB::raw('sum(IFNULL(shipped_quantity,0) - IFNULL(ship_quantity,0)) as quantity'))
            ->groupBy('account_id', 'warehouse_id', 'fnsku')
            ->get();
        $count = count($detailList);
        echo '---总数：'.$count.'......'.PHP_EOL;
        $i = 0;
        foreach ($detailList as $val){
            $removaleInventory = RemovaleInventoryFNSku::query()
                ->where([
                    'account_id' => $val->account_id,
                    'warehouse_id' => $val->warehouse_id,
                    'fnsku' => $val->fnsku,
                ])->first();
            $i++;
            if($removaleInventory){
                $removaleInventory->psku_id = $val->psku_id;
                $removaleInventory->save();
                echo '---'.$i.'更新SKU'.'......'.PHP_EOL;
            }else{
                RemovaleInventoryFNSku::query()->create([
                    'account_id' => $val->account_id,
                    'warehouse_id' => $val->warehouse_id,
                    'fnsku' => $val->fnsku,
                    'psku_id' => $val->psku_id,
                    'transit' => $val->quantity >= 0 ? $val->quantity : 0,
                ]);
                echo '---'.$i.'添加移库数据'.'......'.PHP_EOL;
            }
        }
    }

    public static function testRemovaleOrderDetail1(){
        //2. 验证在途数量是否为0 （res = 汇总在途数量 - 未完结的入库数量）
        // res > 0 ? res : 0;
        $detailList = RemovaleOrderDetail::query()
            ->select('account_id', 'warehouse_id', 'fnsku', 'psku_id', DB::raw('sum(IFNULL(shipped_quantity,0) - IFNULL(ship_quantity,0)) as quantity'))
            ->where('status', 1) //1: 未完结
            ->groupBy('account_id', 'warehouse_id', 'fnsku')
            ->get();

        $count = count($detailList);
        echo '---总数：'.$count.'......'.PHP_EOL;
        $i = 0;
        foreach ($detailList as $val){
            $removaleInventory = RemovaleInventoryFNSku::query()
                ->where([
                    'account_id' => $val->account_id,
                    'warehouse_id' => $val->warehouse_id,
                    'fnsku' => $val->fnsku,
                ])->first();
            if($removaleInventory){
                $removaleInventory->transit = $val->quantity > 0 ? $val->quantity : 0;
                $removaleInventory->save();
                echo '---'.$i.'更新SKU'.'......'.PHP_EOL;
            }else{
                echo '---'.$i.'未匹配到数据'.'......'.PHP_EOL;
            }
            $val->save();

            $i++;
        }
    }

    public static function testRemovaleOrderDetail3(){
        die('stop!');
        //3. 库存与明细的差异数据
        $existSku = [];
        $existArr = [];
        RemovaleInventoryFNSku::query()->orderBy('id')->chunk(500,function ($items)use(&$existSku,&$existArr){
            foreach ($items as $item){
                $count = RemovaleOrderDetail::query()
                    ->where([
                        'account_id' => $item->account_id,
                        'warehouse_id' => $item->warehouse_id,
                        'fnsku' => $item->fnsku,
                    ])->count();
                if(!$count){
                    if(!in_array($item,$existSku)){
                        $existSku[] = $item;
                    }
                    $key = $item->account_id.'-'.$item->fnsku;
                    if(!array_key_exists($key,$existSku)){
                        $account = SysPlatAccount::query()->find($item->account_id);
                        $countryIds = $account->account_country->pluck('country_id') ?? [];
                        $pas = ProductAmazonSku::query()
                            ->whereIn('country_id',$countryIds)
                            ->where('fnsku',$item->fnsku)
                            ->first();
                        $existSku[$key] = $pas ? $pas->psku_id : null;
                    }
                    if(!$existSku[$key])continue;
                    $item->psku_id = $existSku[$key];
                    $item->save();
                }

            }
        });
    }


    public static function totalQuality(){

        $startTime = date('Y-m-01 00:00:00',strtotime('-1 month'));
        $endTime = date('Y-m-t 23:59:59', $startTime);
        echo "<pre>";
        print_r($startTime);
        echo "<pre>";
        print_r($endTime);
        echo "</pre>";
        exit;

        //$startTime = '';
        //$endTime = time();
        //FbaCustomerReturn::query()->select()->->whereBetween('purchase_date', [1, $endTime])
        //$i = 0;
        //ProductSku::query()
        //    ->with('inventory_cn')
        //    ->with('inventory_fba')
        //    ->with('os_box')
        //    ->with('os_removale')
        //    ->with('os_dropshipping')
        //    ->groupBy('product_sku.id')
        //    ->orderBy('product_sku.id')
        //    ->chunkById(500, function ($items) use (&$count,&$i){
        //        DB::beginTransaction();
        //        try{
        //            foreach ($items as $item){
        //                //国内库存
        //                $totalCnInstant = $item->inventory_cn->sum('instant');
        //                $totalCnTransit = $item->inventory_cn->sum('transit');
        //                $totalCnReserve = $item->inventory_cn->sum('reserve');
        //                //FBA库存
        //                $totalFbaInstant = $item->inventory_fba->sum('quantity');
        //                $totalFbaTransit = $item->inventory_fba->sum('inbound');
        //                //海外仓库存（中转）
        //                $totalOsBoxInstant = $item->os_box->sum('instant');
        //                $totalOsBoxTransit = $item->os_box->sum('transit');
        //                $totalOsBoxReserve = $item->os_box->sum('reserve');
        //                //海外仓库存（移库）
        //                $totalOsRemovaleInstant = $item->os_removale->sum('instant');
        //                $totalOsRemovaleTransit = $item->os_removale->sum('transit');
        //                $totalOsRemovaleReserve = $item->os_removale->sum('reserve');
        //                //海外仓库存（代发）
        //                $totalOsDropshippingInstant = $item->os_dropshipping->sum('instant');
        //                $totalOsDropshippingTransit = $item->os_dropshipping->sum('transit');
        //                $totalOsDropshippingReserve = $item->os_dropshipping->sum('reserve');
        //
        //                $flag1 = InventoryTotalSku::query()->updateOrCreate(
        //                    ['psku_id' => $item->id],
        //                    [
        //                        'classify_id' => $item->classify->id ?? 0,
        //
        //                        'cn_instant' => $totalCnInstant,
        //                        'cn_transit' => $totalCnTransit,
        //                        'cn_reserve' => $totalCnReserve,
        //
        //                        'fba_instant' => $totalFbaInstant,
        //                        'fba_transit' => $totalFbaTransit,
        //
        //                        'os_box_instant' => $totalOsBoxInstant,
        //                        'os_box_transit' => $totalOsBoxTransit,
        //                        'os_box_reserve' => $totalOsBoxReserve,
        //
        //                        'os_removale_instant' => $totalOsRemovaleInstant,
        //                        'os_removale_transit' => $totalOsRemovaleTransit,
        //                        'os_removale_reserve' => $totalOsRemovaleReserve,
        //
        //                        'os_dropshipping_instant' => $totalOsDropshippingInstant,
        //                        'os_dropshipping_transit' => $totalOsDropshippingTransit,
        //                        'os_dropshipping_reserve' => $totalOsDropshippingReserve,
        //                    ]
        //                );
        //                if(!$flag1){
        //                    DB::rollBack();
        //                    continue;
        //                }
        //                echo '......'.$i++.'......'.PHP_EOL;
        //            }
        //            DB::commit();
        //        }catch (\Exception $e){
        //            DB::rollBack();
        //            report($e);
        //        }
        //    });
    }

    public static function exeFillData($estimate){

        $areaId = 4;
        $classifyKey = [];
        $skuKey = [];

        //1. 根据比例，将国家品类预估分解到国家sku预估，同步更新国家sku备货表里的预估
        //更新,国家sku预估、国家备货sku及相关信息
        foreach ($estimate as $_estimate){

            $classifyId = $_estimate->classify_id;
            if(!in_array($classifyId,$classifyKey)){
                $classifyKey[] = $classifyId;
            }

            //备货sku(国家)
            $countryStockingSku = CountryStockingSku::query()
                ->where('country_id',$_estimate->country_id)
                ->whereHas('sku',function ($query) use ($classifyId){
                    $query->where('classify_id',$classifyId);
                })->get();
            foreach ($countryStockingSku as $stockingSku){

                $key = $stockingSku->country_id.'_'.$stockingSku->psku_id;
                if(!in_array($stockingSku->psku_id,$skuKey)){
                    $skuKey[] = $stockingSku->psku_id;
                }

                //sku销售比例(国家)
                $ratio = CountryStockingSkuRatio::getRatio($key);

                //sku预估(国家)
                $skuEstimate = CountrySkuEstimate::query()->firstOrNew(['area_psku' => $key]);
                for($i = 0;$i < CountrySkuEstimate::ESTIMATE_NUM; $i++){
                    $estimateNum = intval(round($_estimate->{'estimate_num'.$i} * $ratio));
                    $stockingSku->{'estimate_num'.$i} = $estimateNum;
                    $skuEstimate->{'estimate_num'.$i} = $estimateNum;
                }
                $stockingSku->save();
                $skuEstimate->save();

                $stockingSku->over_stock = CountryStockingSku::getOverStock($stockingSku);
                $stockingSku->over_stock_value = CountryStockingSku::getOverStockValue($stockingSku->over_stock,$stockingSku->unit_price);
                $stockingSku->save();
            }
        }
        sleep(10);

        /********更新EU站点 start***********/
        //2.1 将EU国家品类预估汇总到EU站点品类预估
        //更新,EU_品类
        foreach ($classifyKey as $_classifyId){

            //EU国家品类预估汇总
            $countryClassifyEstimateSum = CountryClassifyEstimate::query()->selectRaw(self::getQueryEstimateStr())->where('classify_id' ,$_classifyId)->first();

            //更新EU站点品类预估
            $areaClassifyEstimate = AreaClassifyEstimate::query()->firstOrNew(['area_id' => $areaId, 'classify_id' => $_classifyId]);
            for($i = 0; $i < AreaSkuEstimate::ESTIMATE_NUM; $i++){
                $areaClassifyEstimate->{'estimate_num'.$i} = $countryClassifyEstimateSum->{'estimate_num'.$i};
            }
            $areaClassifyEstimate->save();
        }

        //2.2 将EU国家sku预估汇总到EU站点sku预估
        //更新,EU_产品
        $EuCountryIds = SysICountry::getCountryIdsByAreaId($areaId)->toArray(); //EU站点下的国家ID
        foreach ($skuKey as $_skuId){
            $classifyId = ProductSku::getValueById($_skuId, 'classify_id');
            if(!$classifyId) continue;

            //EU站点SKU预估
            $areaSkuEstimateObj = AreaSkuEstimate::query()->where(['area_psku'=> $areaId.'_'.$_skuId])->first();
            if(!$areaSkuEstimateObj) continue;

            $areaPskus = [];
            foreach ($EuCountryIds as $euCountryId){
                $areaPskus[] = $euCountryId.'_'.$_skuId;
            }
            //EU国家sku预估(汇总)
            $countrySkuEstimateSum = CountrySkuEstimate::query()->selectRaw(self::getQueryEstimateStr())->whereIn('area_psku', $areaPskus)->first();
            //EU站点备货sku
            $stockingSkuObj = StockingSku::query()->where('area_psku',$areaId.'_'.$_skuId)->first();
            for($i = 0; $i < AreaSkuEstimate::ESTIMATE_NUM; $i++){
                $areaSkuEstimateObj->{'estimate_num'.$i} = $countrySkuEstimateSum->{'estimate_num'.$i};
                $stockingSkuObj->{'estimate_num'.$i} = $countrySkuEstimateSum->{'estimate_num'.$i};
            }
            $areaSkuEstimateObj->save();
            $stockingSkuObj->save();
            $stockingSkuObj->over_stock = StockingSku::getOverStock($stockingSkuObj);
            $stockingSkuObj->over_stock_value = StockingSku::getOverStockValue($stockingSkuObj->over_stock, $stockingSkuObj->unit_price);
            $stockingSkuObj->save();

            //3. 依据EU站点sku预估与EU站点品类预估计算EU站点sku比例
            //EU站点品类预估
            $classifyEstimate = AreaClassifyEstimate::query()->where(['area_id' => $areaId, 'classify_id' => $classifyId])->first();
            $classifyEstimateNum = 0;
            $num = 0;
            for($i = 0; $i < AreaSkuEstimate::ESTIMATE_NUM; $i++){
                $classifyEstimateNum = $classifyEstimate->{'estimate_num'.$i};
                if($classifyEstimateNum != 0){
                    $num = $i;
                    break;
                }
            }
            //EU站点sku销售比例
            $skuRatioObj = StockingSkuRatio::query()->firstOrNew(['area_psku'=> $areaId.'_'.$_skuId]);
            if($classifyEstimateNum != 0){
                $stockingSkuRatio = sprintf("%.4f", $areaSkuEstimateObj->{'estimate_num'.$num} / $classifyEstimateNum);
                $skuRatioObj->ratio = $stockingSkuRatio; //0.3001
                $skuRatioObj->save();
            }
        }
        /********更新EU站点 end**********/
    }


    /**
     * 更新Amazon品类id
     */
    public static function syncCountryClassifyEstimate(){

        die('stop!');

        //$data = CountryClassifyEstimate::query()->orderBy('id')->get();
        //CountryEstimateJob::dispatch($data);
        //
        //echo "<pre>";
        //print_r('over!');
        //echo "</pre>";
        //exit;
    }

    public static function getQueryEstimateStr(){
        //拼接SQL查询字段
        $queryStr = '';
        for($i = 0; $i < AreaSkuEstimate::ESTIMATE_NUM; $i++){
            if ($i < 1) {
                $queryStr .= 'sum(estimate_num'.$i.') as estimate_num'.$i;
            }else{
                $queryStr .= ',sum(estimate_num'.$i.') as estimate_num'.$i;
            }
        }
        return $queryStr;
    }

    public static function saveRemovaleInventoryFnskuTransit(){
        echo "<pre>";
        print_r('aaa');
        echo "</pre>";
        exit;
        RemovaleInventoryFNSku::query()
            ->chunk(100,function ($items){
                foreach ($items as $item){
                    $re = RemovaleOrderDetail::query()
                        ->where('account_id', $item->account_id)
                        ->where('warehouse_id', $item->warehouse_id)
                        ->where('fnsku',$item->fnsku)
                        ->selectRaw('sum(shipped_quantity) as shipped_quantity,sum(in_process_quantity) as in_process_quantity,sum(ship_quantity) as ship_quantity')
                        ->where('status', 1)
                        ->groupBy('account_id','warehouse_id','fnsku')
                        ->first();
                    $transit = ($re->shipped_quantity ?? 0) + ($re->in_process_quantity ?? 0) - ($re->ship_quantity ?? 0);
                    if($transit > 0){
                        $item->transit = $transit;
                        $item->save();
                    }
                }
        });
    }

    /**
     * 库存总表（SKU）
     */
    public static function saveInventoryTotalSku(){

        $i = 0;
        ProductSku::query()
            ->with('inventory_cn')
            ->with('inventory_fba')
            ->with('os_box')
            ->with('os_removale')
            ->with('os_dropshipping')
            ->groupBy('product_sku.id')
            ->orderBy('product_sku.id')
            ->chunkById(500, function ($items) use (&$count,&$i){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        //国内库存
                        $totalCnInstant = $item->inventory_cn->sum('instant');
                        $totalCnTransit = $item->inventory_cn->sum('transit');
                        $totalCnReserve = $item->inventory_cn->sum('reserve');
                        //FBA库存
                        $totalFbaInstant = $item->inventory_fba->sum('quantity');
                        $totalFbaTransit = $item->inventory_fba->sum('inbound');
                        //海外仓库存（中转）
                        $totalOsBoxInstant = $item->os_box->sum('instant');
                        $totalOsBoxTransit = $item->os_box->sum('transit');
                        $totalOsBoxReserve = $item->os_box->sum('reserve');
                        //海外仓库存（移库）
                        $totalOsRemovaleInstant = $item->os_removale->sum('instant');
                        $totalOsRemovaleTransit = $item->os_removale->sum('transit');
                        $totalOsRemovaleReserve = $item->os_removale->sum('reserve');
                        //海外仓库存（代发）
                        $totalOsDropshippingInstant = $item->os_dropshipping->sum('instant');
                        $totalOsDropshippingTransit = $item->os_dropshipping->sum('transit');
                        $totalOsDropshippingReserve = $item->os_dropshipping->sum('reserve');

                        $flag1 = InventoryTotalSku::query()->updateOrCreate(
                            ['psku_id' => $item->id],
                            [
                                'classify_id' => $item->classify->id ?? 0,

                                'cn_instant' => $totalCnInstant,
                                'cn_transit' => $totalCnTransit,
                                'cn_reserve' => $totalCnReserve,

                                'fba_instant' => $totalFbaInstant,
                                'fba_transit' => $totalFbaTransit,

                                'os_box_instant' => $totalOsBoxInstant,
                                'os_box_transit' => $totalOsBoxTransit,
                                'os_box_reserve' => $totalOsBoxReserve,

                                'os_removale_instant' => $totalOsRemovaleInstant,
                                'os_removale_transit' => $totalOsRemovaleTransit,
                                'os_removale_reserve' => $totalOsRemovaleReserve,

                                'os_dropshipping_instant' => $totalOsDropshippingInstant,
                                'os_dropshipping_transit' => $totalOsDropshippingTransit,
                                'os_dropshipping_reserve' => $totalOsDropshippingReserve,
                            ]
                        );
                        if(!$flag1){
                            DB::rollBack();
                            continue;
                        }
                        echo '......'.$i++.'......'.PHP_EOL;
                    }
                    DB::commit();
                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }

    /**
     * 批量更正产品状态 （产品状态：新产品改为正常产品）
     */
    public static function updateProductSkuStatus(){

        //die('stop!');

        //产品状态（新产品）
        $data = ProductSku::query()->where('psku_status', ProductSku::PSKUSTATUS_NEW)->get();

        $n = 0;
        foreach ($data as $key => $val){
            $val->psku_status = ProductSku::PSKUSTATUS_NORMAL; //正常产品
            $val->save();

            $n++;
            echo '......'.$n.'......'.PHP_EOL;
        }

        echo "<pre>";
        print_r('success!!!');
        echo "</pre>";
        exit;
    }

    /**
     * 更新发货方式（发货明细）
     */
   /*public static function updateDeliveryDetailDeliveredAt(){

        die('stop');

        $n = 0;
        $data = CustomerDelivery::query()->get();
        foreach ($data as $key => $val){
            CustomerDeliveryDetail::query()->where('delivery_no', $val->delivery_no)->update([
                'delivered_at' => $val->delivered_at
            ]);

            $n++;
            echo '......'.$n.'......'.PHP_EOL;
        }

        echo "<pre>";
        print_r('success!!!');
        echo "</pre>";
        exit;
    }*/

    /**
     * 更新发货方式（发货明细）
     */
    /*public static function syncDeliveryType(){

        die('stop');

        $n = 0;
        $data = CustomerDelivery::query()->distinct()->groupBy('delivery_no')->get();
        foreach ($data as $key => $val){
            CustomerDeliveryDetail::query()->where('delivery_no', $val->delivery_no)->update([
                'delivery_type' => $val->delivery_type
            ]);

            $n++;
            echo '......'.$n.'......'.PHP_EOL;
        }

        echo "<pre>";
        print_r('success!!!');
        echo "</pre>";
        exit;
    }*/

    /**
     * 更新sku(拆分字段，存储)
     */
    /*public static function syncAreaSkuNew(){

        die('stop');

        $n = 0;
        $data = StockupAreaSkuRatio::query()->get();
        foreach ($data as $key => $val){

            list($areaId, $pSkuId) = explode('_', $val->area_psku);
            $classifyId = ProductSku::getValueById($pSkuId, 'classify_id');
            if (!$classifyId) continue;

            $val->area_id = $areaId;
            $val->psku_id = $pSkuId;
            $val->classify_id = $classifyId;
            if (!$val->save()) continue;

            $n++;
            echo '......'.$n.'......'.PHP_EOL;
        }

        echo "<pre>";
        print_r('success!!!');
        echo "</pre>";
        exit;
    }*/

    /**
     * 更新生成库存（总表）
     */
    public static function updateProductStockup(){

        echo "<pre>";
        print_r(111);
        echo "</pre>";
        exit;
        $data = DB::table('s_area_sku as sku')
            ->leftJoin('s_area_sku_avg as avg','sku.area_psku', '=', 'avg.area_psku')
            ->leftJoin('s_area_sku_estimate as sku_estimate','sku.area_psku','=','sku_estimate.area_psku')
            ->leftJoin('s_area_sku_stock as stock','sku.area_psku','=','stock.area_psku')
            ->select(
                'sku.id', 'sku.area_psku', 'sku.type',
                'avg.avg3', 'avg.avg7', 'avg.avg15', 'avg.avg30', 'avg.avg',
                DB::raw('
                    IFNULL(sku_estimate.estimate_num0, 0) as estimate_num0,
                    IFNULL(sku_estimate.estimate_num1, 0) as estimate_num1,
                    IFNULL(sku_estimate.estimate_num2, 0) as estimate_num2,
                    IFNULL(sku_estimate.estimate_num3, 0) as estimate_num3,
                    IFNULL(sku_estimate.estimate_num4, 0) as estimate_num4,
                    IFNULL(sku_estimate.estimate_num5, 0) as estimate_num5,
                    IFNULL(sku_estimate.estimate_num6, 0) as estimate_num6,
                    IFNULL(sku_estimate.estimate_num7, 0) as estimate_num7,
                    IFNULL(sku_estimate.estimate_num8, 0) as estimate_num8
                '),
                'stock.fba_instant_num', 'stock.fba_transit_num', 'stock.cn_instant_num', 'stock.cn_transit_num', 'stock.os_instant_num', 'stock.os_transit_num'
            )
            ->orderBy('id')
            ->limit(100)
            ->get();

        if ($data) {

            $res = json_decode($data, true);
            $res1 = array_column($res, 'area_psku'); //area_psku基础数据
            $res2 = Stockup::query()->pluck('area_psku')->toArray(); //备货基础数据

            //删除差异数据
            $diffArrayData = array_diff($res1, $res2);
            if ($diffArrayData) {
                foreach ($diffArrayData as $key => $value){
                    Stockup::query()->where('area_psku',$value)->delete();
                }
            }

            $n = 0;
            DB::beginTransaction();
            try{
                foreach ($data as $key => $val){

                    $paramData = self::setStockupColumn($val);
                    if (!$paramData) continue;

                    $res = Stockup::query()->updateOrCreate([
                        'area_psku' => $val->area_psku
                    ],[
                        'area_id'               => $paramData->area_id,
                        'psku_id'               => $paramData->psku_id,
                        'classify_id'           => $paramData->classify_id,
                        'cn_pulic_instant_num'  => $paramData->cn_pulic_instant_num ?? 0,
                        'overstock_num'         => $paramData->overstock_num ?? 0,
                        'cn_stock_total'        => $paramData->cn_stock_total ?? 0,
                        'divert_overstock_num'  => $paramData->divert_overstock_num ?? 0,
                        'divert_instant_num'    => $paramData->divert_instant_num ?? 0,
                        'divert_transit_num'    => $paramData->divert_transit_num ?? 0,
                        'purchase_cycle'        => $paramData->purchase_cycle ?? 0,
                        'sea_day'               => $paramData->sea_day ?? 0,
                        'air_day'               => $paramData->air_day ?? 0,
                        'defer_stock_num'       => $paramData->defer_stock_num ?? 0,

                        'avg3'  => $val->avg3 ?? 0,
                        'avg7'  => $val->avg7 ?? 0,
                        'avg15' => $val->avg15 ?? 0,
                        'avg30' => $val->avg30 ?? 0,
                        'avg'   => $val->avg ?? 0,
                        'current_sale_ratio' => $paramData->current_sale_ratio ?? '0%',
                        'volume30_ratio'     => $paramData->volume30_ratio ?? '0%',

                        'estimate_num0'  => $val->estimate_num0 ?? 0,
                        'estimate_num1'  => $val->estimate_num1 ?? 0,
                        'estimate_num2'  => $val->estimate_num2 ?? 0,
                        'estimate_num3'  => $val->estimate_num3 ?? 0,
                        'estimate_num4'  => $val->estimate_num4 ?? 0,
                        'estimate_num5'  => $val->estimate_num5 ?? 0,
                        'estimate_num6'  => $val->estimate_num6 ?? 0,
                        'estimate_num7'  => $val->estimate_num7 ?? 0,
                        'estimate_num8'  => $val->estimate_num8 ?? 0,
                        'estimate_total' => $paramData->estimate_total ?? 0,

                        'cn_delivery_num0'  => $paramData->cn_delivery_num0 ?? 0,
                        'cn_delivery_num1'  => $paramData->cn_delivery_num1 ?? 0,
                        'cn_delivery_num2'  => $paramData->cn_delivery_num2 ?? 0,
                        'cn_delivery_num3'  => $paramData->cn_delivery_num3 ?? 0,
                        'cn_delivery_num4'  => $paramData->cn_delivery_num4 ?? 0,
                        'cn_delivery_num5'  => $paramData->cn_delivery_num5 ?? 0,
                        'cn_delivery_num6'  => $paramData->cn_delivery_num6 ?? 0,
                        'cn_delivery_num7'  => $paramData->cn_delivery_num7 ?? 0,
                        'cn_delivery_num8'  => $paramData->cn_delivery_num8 ?? 0,

                        'fba_instant_num' => $val->fba_instant_num ?? 0,
                        'fba_transit_num' => $val->fba_transit_num ?? 0,
                        'cn_instant_num'  => $val->cn_instant_num ?? 0,
                        'cn_transit_num'  => $val->cn_transit_num ?? 0,
                        'os_instant_num'  => $val->os_instant_num ?? 0,
                        'os_transit_num'  => $val->os_transit_num ?? 0,
                        'stock_total'     => $paramData->stock_total ?? 0,
                    ]);

                    if (!$res) {
                        DB::rollBack();
                        continue;
                    }

                    $n++;
                    echo '......'.$n.'......'.PHP_EOL;
                }

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }
        }

        //更新分配库存数量
        //self::saveStockPlan();

        echo "<pre>";
        print_r('aaa');
        echo "</pre>";
        exit;
    }

    /**
     * 更新分配库存
     */
    /*public static function saveStockPlan(){
        //回写，需求分配库存(月份)
        $n = 0;
        $stockup = Stockup::query()
            ->select('area_psku','psku_id','classify_id', DB::raw('
                sum(fba_instant_num) as fba_instant_num,
                sum(fba_transit_num) as fba_transit_num,
                sum(os_instant_num) as os_instant_num,
                sum(os_transit_num) as os_transit_num,
                sum(cn_instant_num) as cn_instant_num
            '))
            ->groupBy('psku_id')
            ->orderBy('id')
            ->limit(100)
            ->get();
        if ($stockup) {
            $data = [];
            foreach ($stockup as $key => $val){
                $totl = $val->fba_instant_num + $val->fba_transit_num + $val->os_instant_num + $val->os_transit_num + $val->cn_instant_num;
                $data[$val->psku_id]['stock_total'] = $totl; //库存量
                for ($i = 0; $i <= 8; $i++){
                    //月份发货需求数量（当月的总需求量）
                    $data[$val->psku_id][$i]['cn_delivery_num'.$i] = Stockup::getStockupColumnSum($val->classify_id, 'cn_delivery_num'.$i);

                    //月份发货站点（当月站点的需求量）
                    $areaNumber = Stockup::query()->where('psku_id', $val->psku_id)->pluck('cn_delivery_num'.$i, 'area_id');
                    foreach ($areaNumber as $k => $v){
                        $data[$val->psku_id][$i]['area'][$k] = $v;
                    }
                }

                $paramData = self::setStockPlanColumn($data);
                $res = Stockup::query()->updateOrCreate([
                    'area_psku' => $val->area_psku
                ],[
                    'stock_plan0'  => $paramData->stock_plan0 ?? 0,
                    'stock_plan1'  => $paramData->stock_plan1 ?? 0,
                    'stock_plan2'  => $paramData->stock_plan2 ?? 0,
                    'stock_plan3'  => $paramData->stock_plan3 ?? 0,
                    'stock_plan4'  => $paramData->stock_plan4 ?? 0,
                    'stock_plan5'  => $paramData->stock_plan5 ?? 0,
                    'stock_plan6'  => $paramData->stock_plan6 ?? 0,
                    'stock_plan7'  => $paramData->stock_plan7 ?? 0,
                    'stock_plan8'  => $paramData->stock_plan8 ?? 0,
                ]);

                if (!$res) {
                    DB::rollBack();
                    continue;
                }

                $n++;
                echo 'stock_plan......'.$n.'......'.PHP_EOL;
            }
        }

    }*/

    /**
     * 获取, 需求分配库存(月份)
     * @param $data
     * @return array
     */
    public static function setStockPlanColumn($data){

        //需分配库存
        $params = [];
        foreach ($data as $key => $val){

            $stockTotal = $val['stock_total'] ?? 0; //库存总量
            unset($val['stock_total']);

            foreach ($val as $k => $v){

               $cnMonthNumber = $v['cn_delivery_num'.$k] ?? 0; //当前月
               //首月分配库存数量
               if ($k == 0) {
                   if ($cnMonthNumber <= 0) { //首月中国发货需求数量
                       //首月中国发货需求数量小于0, 则分配库存数量 = 0
                       $params['stock_plan'.$k] = 0;
                   }else{
                       //首月分配库存数量 = （首月中国发货需求数量 - fba在途 - 海外仓在途）
                       $params['stock_plan'.$k] = $cnMonthNumber - $stockTotal;
                   }
               }

               //其它月份分配库存数量
               if ($k > 0) {
                   if ($params['stock_plan'.($k-1)] < 0) { //上月分配数量 < 0, 则上月分配数量累加当月中国发货需求数量。
                       //当月分配数量 = (上月分配数量 + 当月中国发货需求数量)
                       $params['stock_plan'.$k] = $params['stock_plan'.($k-1)] + $cnMonthNumber;

                   }else{
                       //当月分配数量 = 月份发货需求数量
                       $params['stock_plan'.$k] = $cnMonthNumber;
                   }
               }
           }
        }

        return json_decode(json_encode($params));
    }

    public static function setStockPlanColumn1($val){

        //"A:公共库存数量";
        //$inventryNum = 301;
        //"A:1月份各个站点所需要发货数量";
        //$detail1 = ['US' => 100,'EU' => 128,'JP' => 0];
        //"A:2月份各个站点所需要发货数量";
        //$detail2 = [100,128,0];
        //"A:3月份各个站点所需要发货数量";
        //$detail3 = [100,128,0];
        //$count = count($detail1);
        //$sum = sum($detail1);
        //$surplus = $i = 0;
        //foreach ($detail1 as $needShipNum){
        //    $i++;
        //    if($i == $count){
        //        $_thisOrderNum = $inventryNum - $surplus;
        //    }else{
        //        $_thisOrderNum = (int)floor($needShipNum / $sum * $inventryNum);
        //        $surplus += $_thisOrderNum;
        //    }
        //}

        //需分配库存
        $params = [];
        foreach ($val as $sku => $items){
            $stockTotal = $items['stock_total'];//sku在途库存总量
            unset($items['stock_total']);
            $month = 0;
            foreach ($items as $v){
                $sum = $v['cn_delivery_num'.$month] ?? 0; //当月站点总需求量
                if($sum <= 0 || $stockTotal == 0){
                    $params['stock_plan'.$month] = 0;
                    foreach ($v['area'] as $areaId => $num){
                        $params['stock_plan'.$month][$areaId] = 0;
                    }
                }else{
                    if($stockTotal >= $sum){
                        $params['stock_plan'.$month] = $sum;
                        foreach ($v['area'] as $areaId => $num){
                            $params['stock_plan'.$month][$areaId] = $num;
                        }
                        $stockTotal -= $sum;
                    }else{
                        $surplus = $i = 0;
                        $count = count($v['area']);
                        $total = 0;
                        foreach ($v['area'] as $areaId => $needShipNum){
                            $i++;
                            if($i == $count){
                                $_thisOrderNum = $stockTotal - $surplus;
                            }else{
                                $_thisOrderNum = (int)floor($needShipNum / $sum * $stockTotal);
                                $surplus += $_thisOrderNum;
                            }
                            $total += $_thisOrderNum;
                            $params['stock_plan'.$month][$areaId] = $_thisOrderNum;
                        }
                        $params['stock_plan'.$month] = $total;
                        $stockTotal = 0;
                    }
                }
                $month++;
                $params['分配后剩余库存'.$sku] = $stockTotal;

                echo "<pre>";
                print_r($params);
                echo "</pre>";
                exit;
            }

        }

        echo "<pre>";
        print_r('222');
        echo "</pre>";
        exit;

        return json_decode(json_encode($params));
    }


    /**
     * 补充测试数据（一件代发）
     */
    /*public static function createDropshipping(){
        InventoryBox::query()
            ->chunk(500, function ($items) use (&$i){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        $updateobj = DropshippingInventoryFnsku::query()
                            ->updateOrCreate([
                                'account_id' => $item->account_id,
                                'warehouse_id' => $item->warehouse_id,
                                'fnsku' => $item->fnsku,
                                'psku_id' => $item->psku_id,
                            ],[
                                'instant' => 5000
                            ]);
                        if(!$updateobj){
                            DB::rollBack();
                            continue;
                        }

                        echo '......'.$i++.'......'.PHP_EOL;
                    }
                    DB::commit();

                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }*/

    /**
     * 同步汇率,地区
     */
    /*public static function syncExchangeRatePaymentArea(){

        PaymentDetail::query()
            ->selectRaw('report_date,area_id,min(rate_odds) as rate_odds')
            ->groupBy(['report_date', 'area_id'])
            ->chunk(500, function ($items) use (&$i){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        $updateobj = PaymentArea::query()
                            ->where('report_date', $item->report_date)
                            ->where('area_id', $item->area_id)
                            ->update([
                                'rate_odds' => $item->rate_odds
                            ]);
                        if(!$updateobj){
                            DB::rollBack();
                            continue;
                        }

                        echo '......'.$i++.'......'.PHP_EOL;
                    }
                    DB::commit();

                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }*/

    /**
     * 同步汇率,国家
     */
    /*public static function syncExchangeRatePaymentCountry(){

        die('stop');

        $i = 0;
        PaymentDetail::query()
            ->selectRaw('report_date,area_id,min(rate_odds) as rate_odds')
            ->groupBy(['report_date', 'area_id'])
            ->chunk(500, function ($items) use (&$i){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        $updateobj = PaymentCountry::query()
                            ->where('report_date', $item->report_date)
                            ->where('area_id', $item->area_id)
                            ->update([
                                'rate_odds' => $item->rate_odds
                            ]);
                        if(!$updateobj) continue;

                        echo '......'.$i++.'......'.PHP_EOL;
                    }
                    DB::commit();

                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }*/

    /**
     * 同步汇率,品类
     */
    /*public static function syncExchangeRatePaymentClassify(){

        die('stop');

        $i = 0;
        PaymentDetail::query()
            ->selectRaw('report_date,area_id,min(rate_odds) as rate_odds')
            ->groupBy(['report_date', 'area_id'])
            ->chunk(500, function ($items) use (&$i){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        $updateobj = PaymentClassify::query()
                            ->where('report_date', $item->report_date)
                            ->where('area_id', $item->area_id)
                            ->update([
                                'rate_odds' => $item->rate_odds
                            ]);
                        if(!$updateobj) continue;

                        echo '......'.$i++.'......'.PHP_EOL;
                    }
                    DB::commit();

                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }*/

    /**
     * 同步汇率,销售
     */
    /*public static function syncExchangeRatePaymentSeller(){

        die('stop');

        $i = 0;
        PaymentDetail::query()
            ->selectRaw('report_date,area_id,min(rate_odds) as rate_odds')
            ->groupBy(['report_date', 'area_id'])
            ->chunk(500, function ($items) use (&$i){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        $updateobj = PaymentSeller::query()
                            ->where('report_date', $item->report_date)
                            ->where('area_id', $item->area_id)
                            ->update([
                                'rate_odds' => $item->rate_odds
                            ]);
                        if(!$updateobj) continue;

                        echo '......'.$i++.'......'.PHP_EOL;
                    }
                    DB::commit();

                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }*/

    /**
     * 同步亚马逊账号
     */
   /* public static function syncAmazonAccount(){

        die('stop');

        $i = 0;
        AmazonAccount::query()
            ->selectRaw('id, account, created_at, updated_at')
            ->chunk(500, function ($items) use (&$i){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        $res = SysPlatAccount::query()->updateOrCreate(
                            [
                                'account' => $item->account,
                                'plat_id' => SysPlat::PLAT_AMAZON
                            ],
                            [
                                'id' => $item->id,
                                'account' => $item->account,
                                'created_at' => $item->created_at,
                                'updated_at' => $item->updated_at,
                            ]
                        );
                        if (!$res) continue;

                        $i++;
                        echo '......'.$i.'......'.PHP_EOL;
                    }
                    DB::commit();

                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }*/

    /**
     * shopify产品同步至平台产品
     */
    /*public static function syncShopifySku(){

        die('stop');

        $n = 0;
        $platId = SysPlat::PLAT_SHOPIFY; //Shopify
        $countryId = SysCountry::getIdByCountry('US');
        ProductAmazonSku::query()
            ->orderBy('id')
            ->chunk(1000, function ($items) use (&$n, $platId, $countryId){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){

                        //验证公司Sku
                        $productSku = ProductSku::getModelById($item->psku_id);
                        if(!$productSku) continue;

                        //验证平台Sku
                        $platSkuCount = ProductShopifySku::query()
                            ->where('country_id', $countryId)
                            ->where('seller_sku', $productSku->psku_code)
                            ->count();
                        if($platSkuCount > 0) continue;

                        $n++;
                        echo '......第'.$n.'条......'.PHP_EOL;

                        //创建
                        $data = [];
                        $data['seller_sku']   = $productSku->psku_code;
                        $data['country_id']   = $countryId;
                        $data['psku_id']      = $item->psku_id;
                        $data['barcode_type'] = 3;
                        $data['barcode']      = '无';
                        $data['account_id']   = 1;
                        $data['status']       = $item->status;
                        $data['seller_id']    = 33;
                        $data['cuser_id']     = 33;

                        $model = ProductShopifySku::query()->create($data);
                        if(!$model){
                            echo 'error:'.$n.'......'.PHP_EOL;
                            DB::rollBack();
                        }else{
                            $classify_id = ProductSku::getValueById($item->psku_id, 'classify_id');
                            ProductShopifySkuCCS::returnSellerId($countryId, $classify_id, 33);

                            DB::commit();
                        }
                    }

                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }*/

    /**
     * 亚马逊产品同步至平台产品
     */
    /*public static function testSyncAmazon(){

        die('stop');

        $n = 0;
        $platId = SysPlat::PLAT_AMAZON; //亚马逊
        ProductAmazonSku::query()
            ->orderBy('id')
            ->chunk(1000, function ($items) use (&$n, $platId){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        //验证sku
                        $platSkuCount = ProductPlatSku::query()
                            ->where('plat_id', $platId)
                            ->where('country_id', $item->country_id)
                            ->where('seller_sku', $item->psku_code)
                            ->count();
                        if($platSkuCount > 0) continue;

                        echo '---start---：'.$n++.'============='.PHP_EOL;
                        $model = ProductPlatSku::query()->create([
                            'plat_id' => $platId,
                            'seller_sku' => $item->seller_sku,
                            'country_id' => $item->country_id,
                            'psku_id' => $item->psku_id,
                            'barcode_type' => $item->barcode_type,
                            'barcode' => $item->barcode,
                            'part_number' => $item->amazon_part_number,
                            'account_id' => $item->account_id,
                            'parent_asin' => $item->parent_asin,
                            'child_asin' => $item->child_asin,
                            'fnsku' => $item->fnsku,
                            'fan_eu' => $item->fan_eu,
                            'times' => $item->times,
                            'seller_id' => $item->seller_id,
                            'cuser_id' => $item->cuser_id,
                            'status' => $item->status,
                        ]);
                        if(!$model){
                            echo 'error:'.$n.'......'.PHP_EOL;
                            DB::rollBack();
                        }else{
                            DB::commit();
                        }
                    }
                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }*/

    /**
     * shopify产品同步至平台产品
     */
    /*public static function testSyncShopify(){

        die('stop');

        $n = 0;
        $platId = SysPlat::PLAT_SHOPIFY; //Shopify
        $countryId = SysCountry::getIdByCountry('US');
        ProductSku::query()
            ->orderBy('id')
            ->chunk(1000, function ($items) use (&$n, $platId, $countryId){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        //验证sku
                        $platSkuCount = ProductPlatSku::query()
                            ->where('plat_id', $platId)
                            ->where('country_id', $countryId)
                            ->where('seller_sku', $item->psku_code)
                            ->count();
                        if($platSkuCount > 0) continue;

                        echo '......第'.$n++.'条......'.PHP_EOL;

                        //创建
                        $data = [];
                        $data['plat_id']      = $platId;
                        $data['seller_sku']     = $item->psku_code;
                        $data['country_id']   = $countryId;
                        $data['psku_id']      = $item->id;
                        $data['barcode_type'] = 3;
                        $data['barcode']      = '无';
                        $data['part_number']  = $item->part_number ?? '';
                        $data['account_id']   = 1;
                        $data['parent_asin']  = '无';
                        $data['child_asin']   = '无';
                        $data['fnsku']        = null;
                        $data['fan_eu']       = 0;
                        $data['times']        = 0;
                        $data['seller_id']    = 33;
                        $data['cuser_id']     = 33;

                        $model = ProductPlatSku::query()->create($data);
                        if(!$model){
                            echo 'error:'.$n.'......'.PHP_EOL;
                            DB::rollBack();
                        }else{
                            DB::commit();
                        }
                    }
                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }*/

    /**
     * 同步获取平台产品销售
     */
    /*public static function testSyncProductCcs(){

        die('stop');

        $n = 0;
        ProductPlatSku::query()
            ->chunkById(1000, function ($items) use (&$n){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        //验证平台产品销售品类
                        $productskuCSSCount = ProductPlatSkuCCS::query()
                            ->where([
                                'plat_id' => $item->plat_id,
                                'country_id' => $item->country_id,
                                'classify_id' => $item->sku->classify_id
                            ])
                            ->count();
                        if($productskuCSSCount > 0) continue;
                        echo '......第'.$n++.'条......'.PHP_EOL;

                        //创建平台产品销售品类
                        $data = [];
                        $data['plat_id']     = $item->plat_id;
                        $data['country_id']  = $item->country_id;
                        $data['seller_id']   = $item->seller_id;
                        $data['classify_id'] = $item->sku->classify_id;

                        $model = ProductPlatSkuCCS::query()->create($data);
                        if(!$model){
                            echo 'error:'.$n.'......'.PHP_EOL;
                            DB::rollBack();
                        }else{
                            DB::commit();
                        }
                    }
                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            }, 'id');
    }*/


}
